package org.jetlinks.community.mstn.aspectj;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.hswebframework.web.utils.AnnotationUtils;
import org.jetlinks.community.mstn.annotation.Tenant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
//import org.springframework.core.annotation.AnnotationUtils;
//import org.springframework.stereotype.Component;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Aspect
@Order(0)
@Component
@Slf4j
public class TenantAspect {

    @Autowired
    private ApplicationEventPublisher eventPublisher;


    /**
     * 切点为controller包下的所有public方法
     */
    @Pointcut("@annotation(org.jetlinks.community.mstn.annotation.Tenant)")
    public void aop(){}

//    /**
//     * 目标方法调用之前执行
//     * 注意这里不能使用 ProceedingJoinPoint
//     * @param joinPoint
//     */
//    @Before("aop()")
//    public void doBefore(JoinPoint joinPoint){
//        log.info("Before Test");
//    }

//    /**
//     * 目标方法调用之后执行
//     * 注意这里不能使用 ProceedingJoinPoint
//     * @param joinPoint
//     */
//    @After("aop()")
//    public void doAfter(JoinPoint joinPoint){
//        log.info("End Test");
//    }

//

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(tenant)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Tenant tenant, Object jsonResult)
    {
        handleLog(joinPoint, tenant, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(tenant)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Tenant tenant, Exception e)
    {
        handleLog(joinPoint, tenant, e, null);
    }

    protected Mono<Void> handleLog(final JoinPoint joinPoint, Tenant tenant, final Exception e, Object jsonResult){
        //获取类的标记
        Tenant t = AnnotationUtils.findAnnotation(joinPoint.getTarget().getClass(), Tenant.class);
        log.info("class:{}",t.title());
        log.info("class123:{}",jsonResult);

        //方法标记
        log.info("title:{}", tenant.title());
        this.eventPublisher.publishEvent(tenant.title());


        return Mono.empty();

    }
}
